import React, {useContext, useEffect} from 'react';
import {View, Text, Button, Alert} from 'react-native';
import {useMount, useDebounceEffect, useMap, useSafeState} from 'ahooks';
import dayjs from 'dayjs';
import {useRoute} from '@react-navigation/native';
import {useSelector, useDispatch} from 'react-redux';
import {Dialog} from '@rneui/themed';
import RNDI from 'react-native-device-info';
import GlobalContext from '@/GlobalContext';
import {ApiHost, OssHost} from '@/config/common';
import {setKeyGetAccountInfo} from '@/store';
import CheckPoswerStorageReadViewPage from '@/OsPowers/Storage/ReadViewPage';
export default ({children}) => {
  const dispatch = useDispatch();
  const token = useSelector(state => state.token.value);
  const accountInfo = useSelector(state => state.accountInfo.value);
  const deviceInfo = useSelector(state => state.deviceInfo.value);
  const {uniqueId} = deviceInfo || {};

  const [submitLoading, setSubmitLoading] = useSafeState(false);

  const netdiskMapArr = accountInfo?.j_ext_info?.netdisk_map_arr;
  const [netdiskMap, {set, get, setAll}] = useMap(netdiskMapArr);

  const updateMapArr = async () => {
    try {
      const map = new Map(netdiskMapArr);
      if (!map.has(uniqueId)) {
        map.set(uniqueId, {
          deviceName: RNDI.getModel(),
        });
        setSubmitLoading(true);
        let rsObj = undefined;
        try {
          const reqFormData = {
            netdisk_map_arr: [...map],
          };
          let res = await fetch(`${ApiHost}/account/json/save-account-info`, {
            headers: {
              'content-type': 'application/json',
              token: token,
            },
            method: 'POST',
            body: JSON.stringify(reqFormData),
          });
          rsObj = await res.json();
        } catch (e) {
          setSubmitLoading(false);
          Alert.alert('操作失败', e.message);
          return;
        }
        if (!rsObj) {
          setSubmitLoading(false);
          Alert.alert('操作失败', '!rsObj');
          return;
        }
        const {code = 0, msg} = rsObj || {};
        if (code <= 0) {
          Alert.alert('操作失败', msg);
          return;
        }
        dispatch(setKeyGetAccountInfo(Math.random()));
        setTimeout(() => {
          setSubmitLoading(false);
        }, 500);
      }

      setAll(map);
    } catch (e) {
      console.log('网盘.CkList.异常', e.message);
    }
  };

  useMount(() => {
    // console.log('CkList useMount', dayjs().format());
    console.log('netdiskMapArr', netdiskMapArr, dayjs().format());
    updateMapArr();
  });

  useDebounceEffect(
    () => {
      const map = new Map(netdiskMapArr);
      setAll(map);
    },
    [netdiskMapArr],
    {wait: 0},
  );

  if (submitLoading === undefined) {
    return <></>;
  }
  if (submitLoading) {
    return (
      <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
        <Dialog.Loading />
      </View>
    );
  }

  if (!netdiskMap.has(uniqueId)) {
    return (
      <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
        <Text>获取配置异常</Text>
      </View>
    );
  }

  if (1 == 1) {
    return (
      <Text>
        {uniqueId}-{RNDI.getModel()} ABC
      </Text>
    );
  }

  return children;
};
